<?php

namespace App\Http\Controllers\Api;

use App;
use App\Util\Common;
use App\Util\GetMac;
use App\Util\SqlServerUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
 
use Illuminate\Support\Facades\Storage;
use Excel;

class BeijianController extends CommonController
{
    protected $response = [
    		"Error" => 0,
    		"Message" => "Success!",
    		"Data" => []
	];
    private $ConnDB = "" ;
        
    private function getDbConnect(){
    	try {
	    	$DB =   env('DB_DATABASE_YCDB');
	    	$serverConfig = [ "UID" => env("DB_USERNAME_YCDBUSER"), "PWD" => env("DB_PASSWORD_YCDBPASS"), "Database" => $DB];
	    	$conn = sqlsrv_connect(env("DB_HOST_IP"), $serverConfig);
	    	if( $conn ) {
	    	    $this->ConnDB =$conn ;
	    		return $conn;
	    	}else{
	    		return false;
	    	}
    	} catch(Exception  $e) {
    		$content = $e->getMessage();
    		return false;
    	}
    }
    
    /**
    *  库存数量，	库存单价-不含税	 ，最近的采购单价-不含税单价
    * @date: 2023年2月11日 上午11:06:26
    * @author: juyi
    */
    public function getDTDataU8($cInvCode){ 
    //建立连接
        if(empty($this->ConnDB )){
            $serverConnect  = $this-> getDbConnect();
        }else{
            $serverConnect = $this->ConnDB ;
        } 
    if( !$serverConnect ){
    	return false;
    }
    $result =['kucunQty'=>0,'kcPriceNofax'=>0,'zuixinCgPrice'=> 0 ];
    // gz_YU8CB -- 拿到 库存数量，	库存单价-不含税	 ，最近的采购单价-不含税单价
    //取 最新数据 最近的采购单价-不含税单价 iunitprice
    $sql=" select case when iuninvqty- iquantity <0 then icost else  inatunitprice end fpprice , * from (select   top 1 
  (iquantity-isnull(iinvqty,0)) as iuninvqty,   iquantity , cpoid,citemcode,
cmaketime,iunitprice ,inatunitprice  
From zpurpoheader with(nolock) 
inner join zpurpotail with(nolock) on zpurpoheader.poid=zpurpotail.poid   
Where 1=1 and cInvCode  =  '{$cInvCode}' order by cmaketime desc  ) as a

left join (
Select   icost ,dvoudate ,cordercode,citemcode             
  From zpurBillHead with(nolock) 
inner join zpurbilltail with(nolock) on zpurBillHead.pbvid=zpurbilltail.pbvid 
left join om_v_rds_postdegreeforsettle on zpurbilltail.RdsId = om_v_rds_postdegreeforsettle.pautoid  
 Where 1=1  And  CINVCODE = '{$cInvCode}' And  cbustype <> N'委外加工' and cSource =  '采购'  
) b on b.cordercode =a.cpoid and b.citemcode=b.citemcode";
    $res  = SqlServerUtil::execTosqlOK( $serverConnect ,$sql ,2);
    //
    if($res){
    	$result['zuixinCgPrice'] = round($res['fpprice'] ,2);
    }
   
    //库存数量
    $kcSql="  SELECT  sum(a.fAvailQtty) as fAvailQtty, sum(a.iQtty) as iQtty  from 
(select  (CASE WHEN bInvBatch=1 THEN  CASE WHEN bStopFlag =1 OR bGSPStop= 1 THEN 0 ELSE ISNULL(iQuantity,0)- IsNull(fStopQuantity,0) END  - ISNULL(fOutQuantity,0) ELSE  
CASE WHEN bStopFlag =1 OR bGSPStop= 1 THEN 0 ELSE ISNULL(iQuantity,0)- IsNull(fStopQuantity,0) END  - ISNULL(fOutQuantity,0) END) AS fAvailQtty,(iQuantity) AS iQtty
 FROM v_ST_currentstockForReport  CS inner join dbo.Inventory I ON I.cInvCode = CS.cInvCode   
 left join dbo.InventoryClass IC ON IC.cInvCCode = I.cInvCCode LEFT OUTER JOIN dbo.ComputationUnit CU_G ON 
 I.cSTComUnitCode =CU_G.cComUnitCode 
 LEFT OUTER JOIN dbo.ComputationUnit CU_A ON I.cAssComUnitCode = CU_A.cComunitCode 
 LEFT OUTER JOIN dbo.ComputationUnit CU_M ON I.cComUnitCode = CU_M.cComunitCode 
 LEFT OUTER JOIN dbo.Warehouse W ON CS.cWhCode = W.cWhCode 
 left join vendor v1 on v1.cvencode = cs.cvmivencode 
 left join v_aa_enum E1 on E1.enumcode = ISNULL(cs.iExpiratDateCalcu,0) and E1.enumtype=N'SCM.ExpiratDateCalcu' 
 LEFT OUTER JOIN dbo.v_aa_enum E with (nolock) on E.enumcode=convert(nchar,CS.cMassUnit) and E.enumType=N'ST.MassUnit' 
 WHERE  1=1 And I.cInvCode =  '{$cInvCode}' and W.cWhCode not in (399,400,500,501,502,503,504,505)  ) as a ";
    $kcres  = SqlServerUtil::execTosqlOK( $serverConnect ,$kcSql ,2);
    if($kcres){
    	$result['kucunQty'] = round($kcres['fAvailQtty'] ,2);
    }
    
    //库存单价 -- 结存库存单价
    $year = getCurrentTime(5) ;
    $jcdjSql1 ="if (OBJECT_ID('tempdb..#tmpinout') is not null )
Drop Table #tmpinout

Select 6 as i,
cast(INVENTORY.cInvCCode as nvarchar(12)) as Grade ,IA_Subsidiary.cInvCode, cInvAddCode, cInvName,cInvStd,ComputationUnit.CComUnitName,iInvWeight
,cast(sum(ISNULL(Cast(iAInQuantity as decimal(20,2)),0) -ISNULL(Cast(iAOutQuantity as decimal(20,2)),0)) as float) AS QcQuantity
,cast(sum(ISNULL(cast(cast(iAInPrice as decimal(38,10)) as decimal(38,2)),0)-ISNULL(cast(cast(iAOutPrice as decimal(38,10)) as decimal(38,2)),0)) as decimal(20,2)) AS QcPrice,cast(sum(isnull(Cast(iDebitDifCost as decimal(20,2)),0)-isnull(Cast(iCreditDifCost as decimal(20,2)),0)) as decimal(20,2)) as qcDif,cast(0 as float) as InQuantity,cast(0 as decimal(20,2)) as InPrice,CAST(0 as decimal(20,2)) as InDif,cast(0 as float) as OutQuantity,cast(0 as decimal(20,2)) As OutPrice
into #tmpinout   
From IA_Subsidiary with (nolock) 
left join inventory inventory with (nolock) on IA_Subsidiary.cInvCode=Inventory.cInvCode 
left Join ComputationUnit with (nolock) ON inventory.cComunitCode = ComputationUnit.ccomunitcode 
left join warehouse Warehouse with (nolock) on ia_subsidiary.cWhCode=warehouse.cwhcode 
Where cVouType<> N'33' 
and IA_Subsidiary.iyear={$year} and  IA_Subsidiary.cInvCode =  '{$cInvCode}' 
And ( Not IA_SUBSIDIARY.cWhCode is null ) AND  (WareHouse.bInCost = 1 or WareHouse.cwhcode is null)  
And (imonth=0 or (dKeepDate< N'2012-01-01' and iMonth<>0))
group by INVENTORY.cInvCCode,IA_Subsidiary.cInvCode,cInvName,cInvStd,CComUnitName,iInvWeight,cInvAddCode
having (sum(ISNULL(iAInQuantity,0) -ISNULL(iAOutQuantity,0 ))<>0 
or sum(cast(ISNULL(iAInPrice,0) as decimal(38,2))-Cast(ISNULL(iAOutPrice,0) as decimal(38,2)))<>0 
or sum(isnull(iDebitDifCost,0)-isnull(iCreditDifCost,0))<>0)

insert into #tmpinout  
select 6,INVENTORY.cInvCCode, IA_Subsidiary.cInvCode, cInvAddCode, cInvName,cInvStd,ComputationUnit.CComUnitName,iInvWeight
,0 AS QcQuantity,0 AS QcPrice,0 as qcDif,(case bRdFlag when 1 then (case when (iAInQuantity is null) then 0 else iAInQuantity end) else 0 end) as InQuantity
,(case bRdFlag when 1 then (case when (iAInPrice is null) then 0 else cast(cast(iAInPrice as decimal(38,10)) as decimal(38,2)) end) else 0 end) as InPrice
,(case bRdFlag when 1 then (isnull(iDebitDifCost,0)-isnull(iCreditDifCost,0)) else 0 end) as InDif,(case bRdFlag when 0 then (case when (iAOutQuantity is null) then 0 else iAOutQuantity end) else 0 end) as OutQuantity
,(case bRdFlag when 0 then (case when (iAOutPrice is null) then 0 else cast(cast(iAOutPrice as decimal(38,10)) as decimal(38,2)) end) else 0 end) As OutPrice
From IA_Subsidiary with (nolock) left join inventory inventory with (nolock) on IA_Subsidiary.cInvCode=Inventory.cInvCode 
left Join ComputationUnit with (nolock) ON inventory.cComunitCode = ComputationUnit.ccomunitcode 
left join warehouse Warehouse with (nolock) on ia_subsidiary.cWhCode=warehouse.cwhcode 
Where cVouType<> N'33' and iMonth<>0 
and IA_Subsidiary.iyear= {$year} And  IA_Subsidiary.cInvCode = '{$cInvCode}'   
 And ( Not IA_SUBSIDIARY.cWhCode is null ) AND  (WareHouse.bInCost = 1 or WareHouse.cwhcode is null)  And  (dKeepDate>= N'2012-01-01')";

$jcdjSql3=" Select 1 as dee
,case when cast(sum(qcQuantity)+sum(InQuantity)-sum(OutQuantity) as decimal(20,2))=0 then null else 
ltrim(str(cast(cast(sum(qcPrice)+sum(cast(inPrice as decimal(20,2)))-sum(cast(OutPrice as decimal(20,2))) as decimal(20,2))/cast(sum(qcQuantity)+sum(InQuantity)-sum(OutQuantity) as decimal(20,2)) as decimal(20,2)),20,2)) end as jcdj
 from #tmpinout  group by grade,i,#tmpinout.cInvCode,#tmpinout.cInvName,#tmpinout.cInvStd
 ,#tmpinout.CComUnitName,#tmpinout.iInvWeight,#tmpinout.cInvAddCode ";
  
 SqlServerUtil::sqlexecNo( $serverConnect ,$jcdjSql1 );
    $kcdjres3  = SqlServerUtil::execTosqlYes( $serverConnect ,$jcdjSql3 ,2 );
    if($kcdjres3){
    	$result['kcPriceNofax'] = round($kcdjres3['jcdj'],2) ;
    }
    
    // 插入  --  gz_YU8CB
    return $result ;
}
    
    /**
    * 备件信息 获取U8 数据  -- getU8 备件采购部 操作 先同步u8 然后输了价格 再保存
    * 先通过U8拿到 库存数量、库存单价不含税、最近的采购单价不含税 ，更新到 gz_ypeijianentry 
    * ，将主表gz_ypeijian 的fu8 置1 ，已经同步过了。
    * 
    * 库存数量  fqtykc
    * 库存单价不含税  fkucunPrice
    * 最近的采购单价不含税  fcaigouPrice
    * 
    * 现在买需要的采购人民币单价 fcaigouRmbPrice
    * 现在的采购总价 fcaigouAmount
    * @date: 2022年12月28日 下午4:57:10
    * @author: juyi
    */
    public function getU8(Request $request){
    	$FRepKey = $request->get('FRepKey'); 
    	$liushuihao = $request->get('fbillno'); //获取流水号
    	
    	$fbeijianName = $request->get('fbeijianName'); //备件名称
    	$fbeijianCode = $request->get('fbeijianCode'); // 备件代码
    	$fbeijianhao = $request->get('fbeijianhao'); //物料号 
    	$u8 = $request->get('u8');// -1 -- 全部 ，0- 0-300,1-301-600,2-601-900
    	$result =[];
    	//数据库连接 U8
    	// 采购部  --  40004
    	///// //可用的库存数量fqtykykc
    	if($u8 == 0 ){
    	    $bjSql ="select v1.fbillno,v1.FStatus,v1.checkName,v1.fdatetime,v1.fnote,v1.fchuanmin,v1.fchuanhao,
    	    v1.fmodel,v1.fprodectNO,v1.fcustomer,v1.fzhibaoqi, v1.fu8 ,u1.* from gz_Ypeijian  v1
    	    left join gz_YpeijianEntry u1 on u1.finterid = v1.fid where v1.fbillno = '{$liushuihao}' ORDER BY u1.FEntryID
    	    OFFSET 0 ROWS
    	    FETCH NEXT 300 ROWS ONLY	 ";
    	}elseif($u8 == 1){
    	    $bjSql ="select v1.fbillno,v1.FStatus,v1.checkName,v1.fdatetime,v1.fnote,v1.fchuanmin,v1.fchuanhao,
    	    v1.fmodel,v1.fprodectNO,v1.fcustomer,v1.fzhibaoqi, v1.fu8 ,u1.* from gz_Ypeijian  v1
    	    left join gz_YpeijianEntry u1 on u1.finterid = v1.fid where v1.fbillno = '{$liushuihao}' ORDER BY u1.FEntryID
    	    OFFSET 300 ROWS
    	    FETCH NEXT 300 ROWS ONLY	 ";
    	}elseif($u8 == 2){
    	        $bjSql ="select v1.fbillno,v1.FStatus,v1.checkName,v1.fdatetime,v1.fnote,v1.fchuanmin,v1.fchuanhao,
    	        v1.fmodel,v1.fprodectNO,v1.fcustomer,v1.fzhibaoqi, v1.fu8 ,u1.* from gz_Ypeijian  v1
    	        left join gz_YpeijianEntry u1 on u1.finterid = v1.fid where v1.fbillno = '{$liushuihao}' ORDER BY u1.FEntryID
    	        OFFSET 600 ROWS
    	        FETCH NEXT 300 ROWS ONLY ";
    	}else{
    	 $bjSql ="select v1.fbillno, v1.FStatus,v1.checkName,v1.fdatetime,v1.fnote,v1.fchuanmin,v1.fchuanhao,
v1.fmodel,v1.fprodectNO,v1.fcustomer,v1.fzhibaoqi, v1.fu8 ,u1.* from gz_Ypeijian  v1 
left join gz_YpeijianEntry u1 on u1.finterid = v1.fid where v1.fbillno = '{$liushuihao}' ";
    	 }
    	 
    	 $res = SqlServerUtil::execTosqlOK($this->SqlServer, $bjSql );
    	 $result =[] ; 
    	 
    	 try {
	    	if($res){
	    		$result = arraykeyToLower($res);
	    		foreach ( $result as $k =>&$v)
	    		{
	    			$temp =[];
	    			//从系统取数  暂时 写死掉
	    			$temp = $this->getDTDataU8( $v['fbeijianhao']  );
	    			if( empty($temp)){
	    				showMsg(1, "U8 数据库连接失败！" );
	    			}
	    			//备件名称     fbeijianName
	    			// 备件代码   fbeijianCode
	    			//物料号          fbeijianhao  
	    			// $result =['kucunQty'=>0,'kcPriceNofax'=>0,'zuixinCgPrice'=> 0 ];
	//     			$sql = " ";
	//     			SqlServerUtil::execTosqlOK($con, $sql );
	    			$fqtykc =  $temp['kucunQty'] ;  
	    			$fkucunprice = $temp['kcPriceNofax']  ; 
	    			$fcaigouprice = $temp['zuixinCgPrice']  ; 
	    		 
	    			//库存数量  fqtykc
	    			$v['fqtykc'] = $fqtykc ;
	    			//库存单价不含税  fkucunPrice
	    			$v['fkucunprice'] = $fkucunprice ;
	    			//最近 采购单价--不含税  fcaigouPrice
	    			$v['fcaigouprice'] = $fcaigouprice ;
	    			// 可用的库存数量
	    			//可用库存数量小于0，用现在采购单价*（1+利润率）；
	//     			可用库存数量大于0，用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
	    			//成本单价	fcbprice
	//     			if($v['fqtykykc'] <=0){
	//     				//采购单价*（1+利润率）
	//     				$v['fcbprice'] = $v['fcaigourmbprice'] *(1+$v['flrl']/100) ;
	//     			}else{
	//     				$tempprice = $fcaigouprice ;
	//     				//（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
	//     				if($fkucunprice>=$fcaigouprice){
	//     					$tempprice = $fkucunprice;
	//     				}
	//     				$v['fcbprice'] = round( ( $tempprice *1.13 * $v['fqtykykc'] + ($v['fqtyxq'] - $v['fqtykykc'])*$v['fcaigourmbprice']) *(1+$v['flrl']/100)/$v['fqtyxq'] ,2) ; 
	//     			}
	    			//成本总价	 fcbamount
	//     			$v['fcbamount'] = $v['fqtyxq']* $v['fcbprice'] ;
	//,fqtykykc={$v['fqtykykc']} ,fcbprice={$v['fcbprice']} , fcbamount ={$v['fcbamount']} 
	    			$sql = "update gz_ypeijianentry set  fqtykc={$fqtykc},fkucunprice ={$fkucunprice},fcaigouprice={$fcaigouprice}  where  finterid = '{$v['finterid']}' and fentryid ='{$v['fentryid']}'  " ;
	    			SqlServerUtil::sqlexecTosql($this->SqlServer, $sql );
	    			
	    			SqlServerUtil::sqlexecTosql($this->SqlServer, " update gz_ypeijian set  fu8 =1  where  fid = '{$v['finterid']}'  " );
	    			
	    		}
	    		
	    	}
	    	$res1 = SqlServerUtil::execTosqlOK($this->SqlServer, $bjSql );
	    	$result = arraykeyToLower($res1);
	    	showMsg(0,'成功' , $result) ;
    	 }catch(\Exception $e){
//     	 	showMsg(1,'连接失败' , $e->getMessage() ) ;
    	 	echo $e->getMessage();
    	 }
    }
    
    
    /**
    * 备件保存   （先同步u8 然后输了价格 再保存）
    * @date: 2022年12月12日 下午5:35:27
    * @author: juyi
    */
	public function beijianSave(Request $request){
		
		$all = $request->all() ; 
		$main =  _unsetNull($all['formdata']);
		$FRepKey = $request->get('FRepKey');
		$opername  = $request->opername?$request->opername:'' ;
		$allData =$all['tableData'];
		//fbeijiancode: ""
		//fbeijianhao: ""
		//fbeijianname: 
		if(  empty($main['fprodectno'])){
			showMsg(400,'项目号不能为空');
		}
		if(  empty($main['fzhibaoqi'])){
			showMsg(400,'质保期不能为空');
		} 
		$getVexTableColumnData = $this->getVexBillColumn($FRepKey,  $FHeaderFooter = 1  ) ;
		$db = columnBiao($FRepKey);//表名
		$dbEntry = $db.'Entry';
		if($FRepKey == '40001'){
			// 为空 或  物料代码为空
			if(empty($allData)){
				showMsg(400,'表体为空或物料代码/物料名称/物料号不能为空');
			}
			//过滤
			if($allData){
				foreach ($allData as $k1=>$v1 )
				{
					if(empty($v1['fbeijiancode'])){
						showMsg(400,'备件代码不能为空');
					}
					if(  empty($v1['fbeijianhao'])){
						showMsg(400,'物料号不能为空');
					}
					//判断需求数量 fqtyxq
					if($v1['fqtyxq'] <1 ){
						showMsg(400,'备件代码:'.$v1['fbeijiancode'] .' ，需求数量为0，请检查！' ); 
					}
// 					if(empty($v1['fbeijianname'])){
// 						unset($allData[$k1]);
// 					}
				}
			}
			
		//dd($allData);
			// 可用库存数量小于0即无库存 ，用现在采购单价*（1+利润率）；
			// 可用库存数量大于0，用（库存单价与最近的采购单价较高  *1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
			
			// 库存数量 、 库存单价（按系统单价 不含税） 、 最近采购单价（不含税） 、 成本单价 -- 获取 U8 数据
			$insertRecords = array_filter( _unsetNull($allData)) ;
			$sql = "select fbillno,fid from {$db} where fbillno = '{$main['fbillno']}' " ;
			$temp = SqlServerUtil::execTosql($this->SqlServer, $sql,2);
			
			if($temp){
				$tempid = $temp['fid'];
				
				sqlsrv_query($this->SqlServer,"DELETE {$db} WHERE Fid in ({$tempid}) ");
				sqlsrv_query($this->SqlServer,"DELETE {$dbEntry} WHERE  finterid in ({$tempid}) ");
			}
			//dd($temp , $db , $dbEntry ,$tempid );
			// 主表
			$finterid = SqlServerUtil::insertExec($this->SqlServer ,$db , $main);
			
			if(empty($finterid['id']) || $finterid['id'] ==0){
				showMsg(1,'新增失败');
			}
			
			$finterid = $finterid['id'];
			$insData=[];
			foreach ($insertRecords as $k =>&$v)
			{
				foreach ($getVexTableColumnData as $kc=>$vc)
				{
					if( ( empty($v[$vc['frepfld']]) || $v[$vc['frepfld']] =='.00' ) && $vc['freptype'] == 131 ){
						$v[$vc['frepfld']] =0;
					}
					
					if( empty($v[$vc['frepfld']])  && ($vc['freptype'] == 202 || $vc['freptype'] == 200 ) ){
						$v[$vc['frepfld']] = '';
					}
					$insData[$k][$vc['frepfld']] = $v[$vc['frepfld']] ;
				}
				
				if( in_array($FRepKey, ['40001' ] ) ){
					$insData[$k]["finterid"] = $finterid ;
					$insData[$k]["fentryid"] = $k+1 ;
				}
				
				
			}
			
			$this->writeLog(getMkName($FRepKey),'保存' , $FRepKey , $all ,$opername);
			
			SqlServerUtil::sqlsrvAllTosql($this->SqlServer ,$db.'Entry' , $insData);
			
			showMsg(0,'成功');
		}else{
			//编辑修改
			$updateRecords = $request-> updateRecords ;
			$fidField  = 'fid' ;
			// 备件报价(采购部)   40004
			if($FRepKey == '40004'){
				//提示U8 --  fu8
				foreach ($allData as $k1=>$v1 )
				{
					if( $v1['fu8'] == 0 ){
						showMsg(400,'没有获取U8信息，无法保存！');
					}
				}
			}
			
			//采购 利润率
			if($FRepKey == '40004'){
				//
			    $CsData =  $this->getSystemProfile(['FSetlilv','FSetFFAX' ,'FSetHuiLv','FSetHuiLvOyuan','FSetHuiLvRiyuan','FSetHuiLvYingPang','FSetHuiLvFaLang' ]);
				$fsetlilv = $CsData['fsetlilv']; 
				$fsetffax = $CsData['fsetffax']; 
	 		
				$tableData = $request->tableData ;
				if (count($updateRecords ) == 0 && count($tableData)>0 ){
				
				foreach ($tableData as $k =>&$v)
				{
				    $whereMain = [];
				    $where= [];
				    $EntryData = [];
				    $where[$fidField] = $v[$fidField];
				    foreach ($getVexTableColumnData as $kc=>$vc)
				    {
				        if( ( empty($v[$vc['frepfld']]) || $v[$vc['frepfld']] =='.00' ) && $vc['freptype'] == 131 ){
				            $v[$vc['frepfld']] =0;
				        }
				        
				        if( empty($v[$vc['frepfld']])  && ($vc['freptype'] == 202 || $vc['freptype'] == 200 ) ){
				            $v[$vc['frepfld']] = '';
				        }
				        $EntryData[$vc['frepfld']] = $v[$vc['frepfld']] ;
				    }
				 
				        if($v['fqtyxq']< $v['fqtykykc']){
				            showMsg(400,'可用库存数大于需求数量') ;
				        }
				        $tempprice =0;
				        
				        $EntryData['flrl'] = $fsetlilv ;
				        //现在买需要的采购人民币单价 
				        $v['fcaigourmbprice'] = getbbPrice($v['fwaibi'] ,$CsData ,$v['fcaigouybprice']   );
				        $v['fcaigouamount'] =  $v['fqtyxq']   * $v['fcaigourmbprice']  ;
				        
				        $EntryData['fcaigourmbprice'] = $v['fcaigourmbprice'];
				        $EntryData['fcaigouamount'] = $v['fcaigouamount'];
				        // 成本单价	fcbprice
				        if($v['fqtykykc'] <=0){
				            // 		    				可用库存数量小于0，用现在买需要的采购人民币单价*（1+利润率）；可用库存数量大于0，用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
				            //采购单价*（1+利润率）   fcaigourmbprice  现在买需要的采购人民币单价*（1+利润率）
				            $EntryData['fcbprice'] = $v['fcaigourmbprice'] *(1+$EntryData['flrl']/100) ;
				        }else{
				            $tempprice = $v['fcaigouprice'] ;
				            //（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
				            //用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
				            if($v['fkucunprice']>=$v['fcaigouprice']){
				                $tempprice = $v['fkucunprice'];
				            }
				            $EntryData['fcbprice'] = round( (( $tempprice *(1+$fsetffax/100) * $v['fqtykykc'] + ($v['fqtyxq'] - $v['fqtykykc'])*$v['fcaigourmbprice']) *(1+$EntryData['flrl']/100))/$v['fqtyxq'] ,2) ;
				        }
				        // 成本总价fcbamount
				        $EntryData['fcbamount'] = $v['fqtyxq']* $EntryData['fcbprice'] ;
				        // 						dd($v);
				        unset($EntryData['fid']);
				     
				    
				    $up[] = SqlServerUtil::exeupdateTosql($this->SqlServer,$db.'Entry', $EntryData, $where);
				    $this->writeLog(getMkName($FRepKey),'修改' , $FRepKey , $EntryData ,$opername );
				    
				}
				showMsg(0,'修改成功-采购');
				    
				    
				}
			}

			if($updateRecords){
				foreach ($updateRecords as $k =>&$v)
				{
					
					$whereMain = [];
					$where= [];
					$EntryData = [];
					$where[$fidField] = $v[$fidField];
					foreach ($getVexTableColumnData as $kc=>$vc)
					{
						if( ( empty($v[$vc['frepfld']]) || $v[$vc['frepfld']] =='.00' ) && $vc['freptype'] == 131 ){
							$v[$vc['frepfld']] =0;
						}
						
						if( empty($v[$vc['frepfld']])  && ($vc['freptype'] == 202 || $vc['freptype'] == 200 ) ){
							$v[$vc['frepfld']] = '';
						}
						$EntryData[$vc['frepfld']] = $v[$vc['frepfld']] ;
					}
					if($FRepKey == '40004'){
						if($v['fqtyxq']< $v['fqtykykc']){
							showMsg(400,'可用库存数大于需求数量') ;
						}
						$tempprice =0;
						
						$EntryData['flrl'] = $fsetlilv ; 
						// 成本单价	fcbprice
		    			if($v['fqtykykc'] <=0){
// 		    				可用库存数量小于0，用现在买需要的采购人民币单价*（1+利润率）；可用库存数量大于0，用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
		    				//采购单价*（1+利润率）   fcaigourmbprice  现在买需要的采购人民币单价*（1+利润率）
		    				$EntryData['fcbprice'] = $v['fcaigourmbprice'] *(1+$EntryData['flrl']/100) ;
		    			}else{
		    				$tempprice = $v['fcaigouprice'] ;
		    				//（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
		    				//用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
		    				 if($v['fkucunprice']>=$v['fcaigouprice']){
		    				 	$tempprice = $v['fkucunprice'];
		    				}
		    				$EntryData['fcbprice'] = round( (( $tempprice *(1+$fsetffax/100) * $v['fqtykykc'] + ($v['fqtyxq'] - $v['fqtykykc'])*$v['fcaigourmbprice']) *(1+$EntryData['flrl']/100))/$v['fqtyxq'] ,2) ;
		    			}
						// 成本总价fcbamount
		    			$EntryData['fcbamount'] = $v['fqtyxq']* $EntryData['fcbprice'] ;
// 						dd($v);
		    			unset($EntryData['fid']);
					}
// 					dd($EntryData , $where,$v);
					if($FRepKey == '40005'){
						//财务 
						//成本总价  =  成本单价* 需求数量
						$EntryData['fcbamount'] = $v['fcbprice']*$v['fqtyxq'];
					}
// 					dd($EntryData, $where);
					$up[] = SqlServerUtil::exeupdateTosql($this->SqlServer,$db.'Entry', $EntryData, $where);
					$this->writeLog(getMkName($FRepKey),'修改' , $FRepKey , $EntryData ,$opername );
// 					if($FRepKey == '40004'){
						//SqlServerUtil::sqlexecTosql($this->SqlServer, " update gz_ypeijian set  fu8 = 0  where  fid = '{$v['finterid']}'  " );
// 					}
					
				}
			}
// 			if($up){
// 				showMsg(0,'修改成功');
// 			}
// 			showMsg(1,'修改失败');
			
			showMsg(0,'修改成功');
		}
		
    }
    
    public function beijianEdit(Request $request){
    	$fbillno =$request->fbillno ; 
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$opername  = $request->opername?$request->opername:'' ;
    	
    	$fbillnoStr = " and v1.fbillno = '{$fbillno}' " ;
    	$sqlData = getfileSql($FRepKey ,1);
    	if(!$sqlData){
    		showMsg(1,'设置Sql不存在');
    	}
    	$sql= $sqlData ;
    	$vowels = array("\n", "\r", "\t");
    	$sql = str_replace($vowels, ' ',$sql);
    	
    	$sql = str_replace('{$fbillno}', $fbillnoStr, $sql);
    	$result =[];
    	$res = SqlServerUtil::execTosqlOK($this->SqlServer,$sql);
    	if($res){
    		$result = arraykeyToLower($res);
    		foreach ($result as $k => &$v)
    		{
    			foreach ($v as $k1=>$v1)
    			{
    				if( $v[$k1] ==='.00' ){
    					$v[$k1] = floatval($v1);
    				}
    			}
    		}
    	}
    	showMsg(0,'成功',$result);
    }
    
    public function beijianDel(Request $request){
    	$finterid =$request->finterid ;
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$opername  = $request->opername?$request->opername:'' ;
    	
    	$fmainid =$request->fmainid ;
    	$db = columnBiao($FRepKey);//表名
    	$finteridStr = " and v1.fid = {$finterid}" ;
    	// 启动事务
//     	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
//     		die(print_r(sqlsrv_errors(), true));
//     	}
    	
    	$opername  = $request ->get('opername')?$request ->get('opername') :'';
    	$data  = $request ->get('data');
    	$qkid = sqlsrv_query($this->SqlServer,"DELETE {$db} WHERE Fid in ({$fmainid}) ");
    	$dbentry  =$db.'entry'; 
    	$qkidentry = sqlsrv_query($this->SqlServer,"DELETE {$dbentry} WHERE finterid in ({$finterid}) ");
//     	if($qkid && $qkidentry){
//     		sqlsrv_commit($this->SqlServer);
//     		$this->writeLog(getMkName($FRepKey),'删除' , $FRepKey , $data ,$opername);
    		showMsg(200,'删除成功');
//     	}else{
//     		sqlsrv_rollback($this->SqlServer);
//     		showMsg(400,'删除失败');
//     	}
    	
    }
    
    
    public function beijianStatus(Request $request){
    	$finterid =$request->finterid ;
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$db = columnBiao($FRepKey);//表名
    	$opername  = $request->opername?$request->opername:'' ;
     
    	$FIDStr='';
    	$FItemidStr='';
    	if ($request->has('finterid') and $request->finterid != '' and !empty($request->finterid)) {
    		 
    		$FIDStr=" and fid in ($finterid) ";
//     		$FItemidStr=" and fitemid in ($FID) ";
    		$FItemidStr= $FIDStr ; 
    	}
    	$Fstatus = $request->get('Fstatus'); //1--审核，0--反审
    	$loginname = $opername;
    	$data  = $request ->get('data');
    	$now = getCurrentTime();
    	
    	if(in_array($FRepKey, [ '40001']) ){
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 1){
    					showMsg(400,'不能反审，等待技术、采购、财务反审或退审。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set Fstatus = '{$Fstatus}', checkName = '', ftypebaojia1 = '{$Fstatus}', ftypeCheck = 0, checktimeSC= null where 1=1 {$FItemidStr}  ";
    		}else{
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    				
    				if($v['ftypecheck']> 1){
    					showMsg(400,'不能审核，等待技术 反审。');
    				}
    				
    			}
    			$sql="update {$db} set Fstatus = '{$Fstatus}', checkName = '{$loginname}' , ftypebaojia1 = '{$Fstatus}', ftypeCheck = 1, checktimeSC= '{$now}'  where 1=1 {$FItemidStr}   ";
    		}
    		
    	}elseif(in_array($FRepKey, [ '40002']) ){
    		//备件 技术 部
    		$opernamejs = '已确认' ;
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 2){
    					showMsg(400,'不能反审，等待采购、财务反审或退审。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,'流水号：'.$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set fbeijianJS='',   Fstatus2 = '{$Fstatus}',Fstatus = '{$Fstatus}', checkNameJS = '', ftypebaojia2 = '{$Fstatus}', ftypeCheck = 0, checktimeJS= null, checktimeSC= null  where 1=1 {$FItemidStr}   ";
    		}else{
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400, '流水号：'.$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    				if($v['ftypecheck']> 2){
    					showMsg(400,'不能审核，等待采购 反审完。');
    				}
    			}
    			$sql="update {$db} set fbeijianJS='{$opernamejs}',  Fstatus2 = '{$Fstatus}', checkNameJS = '{$loginname}', ftypebaojia2 = '{$Fstatus}', ftypeCheck = 2, checktimeJS= '{$now}'  where 1=1 {$FItemidStr}   ";
    		}
    		
    	}elseif(in_array($FRepKey, [ '40004']) ){
//     		//备件采购部  -- 
    		$opernamecg = '已确认' ;
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 3){
    					showMsg(400,'流水号：'.$v['fbillno'].'不能反审核，等待财务反审或退审。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,'流水号：'.$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			
    			$sql="update {$db} set fbeijianJS ='', fbeijianCG = '',   Fstatus4 = '{$Fstatus}',Fstatus2 = '{$Fstatus}',  checkNameCG = '', ftypebaojia4 = '{$Fstatus}', ftypeCheck = 1 , fu8=0 , checktimeCG= null, checktimeJS= null where 1=1 {$FItemidStr}   ";
    		}else{
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400,'流水号：'.$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    				if($v['ftypecheck']> 3){
    					showMsg(400,'流水号：'.$v['fbillno'].'不能审核，等待财务 反审或退审。');
    				}
    				if($v['fu8'] < 1){
    					showMsg(400,'流水号：'.$v['fbillno'].' , 未获取U8数据，请重新检查！。');
    				}
    				
    			}
    			$sql="update {$db} set  fbeijianCG = '{$opernamecg}',   Fstatus4 = '{$Fstatus}' , checkNameCG = '{$loginname}' ,ftypebaojia4 = '{$Fstatus}', ftypeCheck = 3 , checktimeCG= '{$now}'  where 1=1 {$FItemidStr}   ";
    		}
    		
    	}elseif(in_array($FRepKey, [ '40005']) ){
    		// 备件 财务部 
    		$opernamecw = '已确认' ;
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			
    			$sql="update {$db} set fbeijianCG='',  fbeijianCW = '',  Fstatus5 = '{$Fstatus}',Fstatus4 = '{$Fstatus}', checkNameCW = '', ftypebaojia5 = '{$Fstatus}' , ftypeCheck = 2, fu8=0 , checktimeCW= null , checktimeCG= null  where 1=1 {$FItemidStr}   ";
    		}else{
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set  fbeijianCW = '{$opernamecw}',   Fstatus5 = '{$Fstatus}',  checkNameCW = '{$loginname}',ftypebaojia5 = '{$Fstatus}' , ftypeCheck = 4 , checktimeCW= '{$now}'   where 1=1 {$FItemidStr}   ";
    		}
    		
    	}
//     	echo $sql;die;
    	// 启动事务
    	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
    		die(print_r(sqlsrv_errors(), true));
    	}
    	
    	$this->writeLog(getMkName($FRepKey),$Fstatus?'审核':'反审核' , $FRepKey ,$request->all() ,$loginname );
    	
    	$sqlStr = iconv( 'UTF-8','GBK',$sql);
    	$up = sqlsrv_query($this->SqlServer, $sqlStr);
    	if($up ){
    		sqlsrv_commit($this->SqlServer);
    		showMsg(0,'成功');
    	}else {
    		sqlsrv_rollback($this->SqlServer);
    		showMsg(1,'失败');
    	}
    	 
    }
    
    //反审
    public function UnCheckFstatus(Request $request){
    	$finterid =$request->finterid ;
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$db = columnBiao($FRepKey);//表名
    	$opername  = $request->opername?$request->opername:'' ;
    	
    	$FIDStr='';
    	$FItemidStr='';
    	if ($request->has('finterid') and $request->finterid != '' and !empty($request->finterid)) {
    		
    		$FIDStr=" and fid in ($finterid) ";
    		//     		$FItemidStr=" and fitemid in ($FID) ";
    		$FItemidStr= $FIDStr ;
    	}
    	$Fstatus = $request->get('Fstatus'); //1--审核，0--反审
    	$loginname = $opername;
    	$data  = $request ->get('data');
    	
    	if(in_array($FRepKey, [ '40001']) ){
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 1){
    					showMsg(400,'不能反审，等待技术、采购、财务反退审完。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set  checkName = '', Fstatus = '{$Fstatus}', ftypebaojia1 = '{$Fstatus}', ftypeCheck = 0, checktimeSC= null  where 1=1 {$FItemidStr}  ";
    		}
    		
    	}elseif(in_array($FRepKey, [ '40002']) ){
    		//备件 技术 部
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 2){
    					showMsg(400,'不能反审，等待采购、财务反退审完。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set fbeijianJS='',checkNameJS = '', Fstatus2 = '{$Fstatus}', ftypebaojia2 = '{$Fstatus}', ftypeCheck = 1 , checktimeJS= null where 1=1 {$FItemidStr}   ";
    		}
    		
    	}elseif(in_array($FRepKey, [ '40004']) ){
    		//备件采购部
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['ftypecheck']> 3){
    					showMsg(400,'不能反审，等待财务反退审完。');
    				}
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			$sql="update {$db} set  fbeijianCG = '',checkNameCG = '', Fstatus4 = '{$Fstatus}',  ftypebaojia4 = '{$Fstatus}', ftypeCheck = 2, checktimeCG= null  where 1=1 {$FItemidStr}   ";
    		} 
    		
    	}elseif(in_array($FRepKey, [ '40005']) ){
    		// 备件 财务部
    		if($Fstatus == 0){
    			foreach ($data as $k=>$v)
    			{
    				if($v['fisqr']> 0){
    					showMsg(400,$v['fbillno'].' ,该订单已经完成，无法操作。');
    				}
    			}
    			
    			$sql="update {$db} set  fbeijianCW = '', checkNameCW ='',  Fstatus5 = '{$Fstatus}' ,  ftypebaojia5 = '{$Fstatus}' ,  ftypeCheck = 3, checktimeCW= null   where 1=1 {$FItemidStr}   ";
    		}  
    		
    	}
    	// 启动事务
    	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
    		die(print_r(sqlsrv_errors(), true));
    	}
    	$sqlStr = iconv( 'UTF-8','GBK',$sql);
    	$up = sqlsrv_query($this->SqlServer, $sqlStr);
    	if($up ){
    		sqlsrv_commit($this->SqlServer);
    		showMsg(0,'成功');
    	}else {
    		sqlsrv_rollback($this->SqlServer);
    		showMsg(1,'失败');
    	}
    	
    	
    }
    
    //完成  -- 未完成 按钮 
    public function wancheng(Request $request){
    	$data = $request->data;
    	$finterid =$request->finterid ;
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$db = columnBiao($FRepKey);//表名
    	$opername  = $request->opername?$request->opername:'' ;
    	$loginname = $opername;
    	$FItemidStr ="" ;
    	if ($request->has('finterid') and $request->finterid != '' and !empty($request->finterid)) {
    		$FItemidStr=" and fid in ($finterid) ";
    	}
    	$fisqr =$request->fisqr??0 ;
    	 
    	if($data['ftypecheck'] <= 3){
    		showMsg(400,'该订单'.$data['fbillno'].'未报价完');
    	}
    	
    	if($fisqr == 0 ){
    		//未完成 
    		$sql="update {$db} set Fisqr = 0,ftypeCheck =4,fisqrName =''  where 1=1 {$FItemidStr}   ";
    	}else{
    		$sql="update {$db} set Fisqr = 1,ftypeCheck =5, fisqrName ='已完成' where 1=1 {$FItemidStr}   ";
    	}
    	// 启动事务
    	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
    		die(print_r(sqlsrv_errors(), true));
    	}
    	 
    	$sqlStr = iconv( 'UTF-8','GBK',$sql);
    	$up = sqlsrv_query($this->SqlServer, $sqlStr);
    	if($up ){
    		sqlsrv_commit($this->SqlServer);
    		showMsg(0,'成功');
    	}else {
    		sqlsrv_rollback($this->SqlServer);
    		showMsg(1,'失败');
    	}
    	
    	
    	
    }
    
    /**
    * 文件用途描述
    * @date: 2023年2月11日 上午9:35:51
    * @author: juyi
    */
    public function tuihui(Request $request){
    	
    	$finterid =$request->finterid ;
    	$FRepKey = $request->FRepKey; // 26005--清单
    	$db = columnBiao($FRepKey);//表名
    	$opername  = $request->opername?$request->opername:'' ;
    	$loginname = $opername;
    	$FItemidStr ="" ;
    	if ($request->has('finterid') and $request->finterid != '' and !empty($request->finterid)) {
    		$FItemidStr=" and fid in ($finterid) ";
    	}
    	$Fstatus = $request->fstatus??0 ; 
    	$data = $request->data;
    	if($data){
    		foreach ($data  as $k =>$v){
    			//只有再未报价状态才能退回 
    			if(in_array($FRepKey, [ '40002'])){
    				if($v['ftypecheck']>1){
    					showMsg(1,'无法退回上一级，正在报价中');
    				}
    				if(  ($v['ftypebaojia4'] == 1 || $v['ftypebaojia5'] == 1) ){
    					showMsg(1,'无法退回 下一级，正在报价中');
    				}
    				
    				if($v['fstatus2'] == 1 ){
    					showMsg(1,'先反审再退回');
    				}
    				
    				break;
    			}
    			
    			if(in_array($FRepKey, [ '40004'])){
    				if($v['ftypecheck']>2){
    					showMsg(1,'无法退回下一级，正在报价中');
    				}
    				if(   $v['ftypebaojia5'] == 1  ){
    					showMsg(1,'无法退回 下一级，正在报价中');
    				}
    				
    				if($v['fstatus4'] == 1 ){
    					showMsg(1,'先反审再退回');
    				}
    				
    				break;
    			}
    			
    			if(in_array($FRepKey, [ '40002'])){
    				if($v['fstatus5'] == 1 ){
    					showMsg(1,'先反审再退回');
    				}
    				
    				break;
    			}
    		}
    	}
    	
    	if(in_array($FRepKey, [ '40002']) ){
    		$sql="update {$db} set Fstatus = '0', checkName = '{$loginname}' ,ftypebaojia1 = '1', ftypeCheck = 1 where 1=1 {$FItemidStr}   ";
    	}elseif(in_array($FRepKey, [ '40004']) ){
    		$sql="update {$db} set Fstatus2 = '0', checkName = '{$loginname}' ,ftypebaojia2 = '1', ftypeCheck = 2 where 1=1 {$FItemidStr}   ";
    	}elseif(in_array($FRepKey, [ '40005']) ){
    		$sql="update {$db} set Fstatus4 = '0', checkName = '{$loginname}',ftypebaojia4 = '1' , ftypeCheck = 3 where 1=1 {$FItemidStr}   ";
    	}
    	// 启动事务
    	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
    		die(print_r(sqlsrv_errors(), true));
    	}
    	
    	$this->writeLog(getMkName($FRepKey),$Fstatus?'审核':'反审核' , $FRepKey ,$request->all() ,$loginname );
    	
    	$sqlStr = iconv( 'UTF-8','GBK',$sql);
    	$up = sqlsrv_query($this->SqlServer, $sqlStr);
    	if($up ){
    		sqlsrv_commit($this->SqlServer);
    		showMsg(0,'成功');
    	}else {
    		sqlsrv_rollback($this->SqlServer);
    		showMsg(1,'失败');
    	}
    	
    	
    }
    
    
    // 用户名  -- tree 结构
    public function beijianTree(Request $request){
    	//label: '二级 1-1', children: [{ id: 9, label: '三级 1-1-1' }, { id: 10, label: '三级 1-1-2' }] 
    	
    	$sql ="select ad.id, ad.username , ad.company,ad.fdeptname,ad.fphone,sub.fid  from gz_admin ad 
				left join gz_SubMessage sub on sub.FName = ad.fdeptname and sub.FTypeID = 30  where ad.username !='manager'				 ";
    	$data = SqlServerUtil::execTosql($this->SqlServer,$sql);
    	
    	$tree = listToTree($data,'fdeptname');
    	showMsg(0,'成功' , $tree);
    	
    }
    
    /**
    * 备件导入
    * @date: 2023年3月9日 上午9:37:40
    * @author: juyi
    */
    public function beijianImport(Request $request){ 
    	$FRepKey = $request->get('FRepKey');
    	$opername= $request->get('opername');
    	$data =  $request->all() ;
    	$insertRecords = $data['data']; //表体
    	$headerData = $data['headerData']; //表头
    	
    	$getVexTableColumnData = $this->getVexBillColumn($FRepKey,  $FHeaderFooter = 1  ) ;
    	$db = columnBiao($FRepKey);//表名
    	if(empty($insertRecords)){
    		showMsg(400,'数据为空，请检查');
    	}
    	if(  empty($headerData['fprodectno'])){
    		showMsg(400,'项目号不能为空');
    	}
    	if(  empty($headerData['fzhibaoqi'])){
    		showMsg(400,'质保期不能为空');
    	}
    	//质保期
    	if(!FISgetYueFenValue($headerData['fzhibaoqi'])) {
    		$arr =['0月','1月','2月' ,'3月','4月','5月','6月','7月','8月','9月','10月','11月','12月' ];
    		showMsg(400,'质保期 : '.$headerData['fzhibaoqi'].' ,不在 '.join(',',$arr ));
    	}
    	
    	
    	$dbEntry = $db.'Entry';
    	$insertRecords =  arraykeyToLower($insertRecords);
    	foreach ($insertRecords as $k1=>$v1)
    	{
    		if(empty($v1['fbeijiancode'])){
    			showMsg(400,'备件代码不能为空');
    		}
    		if(  empty($v1['fbeijianhao'])){
    			showMsg(400,'物料号不能为空');
    		}
    	}
//     	if($temp){
//     		$tempid = $temp['fid'];
    		
//     		sqlsrv_query($this->SqlServer,"DELETE {$db} WHERE Fid in ({$tempid}) ");
//     		sqlsrv_query($this->SqlServer,"DELETE {$dbEntry} WHERE  finterid in ({$tempid}) ");
//     	}
    	// 主表
    	// 启动事务
    	if (sqlsrv_begin_transaction($this->SqlServer) === false) {
    		die(print_r(sqlsrv_errors(), true));
    	}
    	$finterid = SqlServerUtil::insertExec($this->SqlServer ,$db , $headerData);
    	
    	if(empty($finterid['id']) || $finterid['id'] ==0){
    		showMsg(1,'新增失败,请重试');
    	}
    	
    	
    	$finterid = $finterid['id'];
    	$insData=[];
    	foreach ($insertRecords as $k =>&$v)
    	{
    		foreach ($getVexTableColumnData as $kc=>$vc)
    		{
    			if( ( empty($v[$vc['frepfld']]) || $v[$vc['frepfld']] =='.00' ) && $vc['freptype'] == 131 ){
    				$v[$vc['frepfld']] =0;
    			}
    			
    			if( empty($v[$vc['frepfld']])  && ($vc['freptype'] == 202 || $vc['freptype'] == 200 ) ){
    				$v[$vc['frepfld']] = '';
    			}
    			$insData[$k][$vc['frepfld']] = $v[$vc['frepfld']] ;
    		}
    		
    		if( in_array($FRepKey, ['40001' ] ) ){
    			$insData[$k]["finterid"] = $finterid ;
    			$insData[$k]["fentryid"] = $k+1 ;
    		}
    		//判断需求数量 fqtyxq
    		if($v['fqtyxq'] <1 ){
    			showMsg(400,'备件代码:'.$v['fbeijiancode'] .' ，需求数量为0，请检查！' );
    		}
    		
    	}
//     	dd($headerData ,$insData , $db);
    	$inEntry = SqlServerUtil::sqlsrvAllTosql($this->SqlServer ,$db.'Entry' , $insData);
    	$this->writeLog(getMkName($FRepKey),'保存' , $FRepKey , $data ,$opername);
    	
    	if($inEntry  ){
    		sqlsrv_commit($this->SqlServer);
    		showMsg(0,'成功');
    	}else {
    		sqlsrv_rollback($this->SqlServer);
    		showMsg(1,'失败');
    	}
    }
    
    /**
    * 文件用途描述
     case '人民币':
          this.calculatePrice(row, column, 0, 1)
          break
        case '美元': fsethuilv
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilv * 1.06)
          break
        case '欧元': fsethuilvoyuan
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvoyuan * 1.06)
          break
        case '日元': fsethuilvriyuan
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvriyuan * 1.06)
          break
        case '英镑': fsethuilvyingpang
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvyingpang * 1.06)
          break
        case '瑞士法郎': fsethuilvfalang
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvfalang * 1.06)
                    税率 --fsetffax 
         // 原币
                现在采购的采购原币单价(fcaigouybprice) = 现在买需要的采购人民币单价(fcaigourmbprice)
                现在的采购总价(fcaigouamount)   = 需求数量(fqtyxq) * 现在买需要的采购人民币单价(fcaigourmbprice) 
                
                汇率*1.06 
        const fcaigourmbprice = Number(row.fcaigouybprice) * hv * (1 + fsetffax / 100)
        const fcaigouamount = Number(row.fqtyxq) * fcaigourmbprice
        
    * @date: 2024年6月20日 下午6:53:07
    * @author: Administrator
    */
    public function beijianCGImport(Request $request){ 
        $FRepKey = $request->FRepKey ;
        $data = $request->data ;
        $opername = $request->opername ;
        $inEntry = true ; 
        // 启动事务
        if (sqlsrv_begin_transaction($this->SqlServer) === false) {
            die(print_r(sqlsrv_errors(), true));
        }
        $Tlog = []; 
        //取参数问题
        $CsData =  $this->getSystemProfile();
        //汇率
        $fsetffax = $CsData['fsetffax']; 
        $fsetlilv = $CsData['fsetlilv']; 
//         dd($CsData ,$data  ); 
        if($FRepKey == 40004 ){
           if(count($data)>0 && $data){
               //fprodectno
               $fbillnoArr = SqlServerUtil::execTosql($this->SqlServer,"select fid as finterid,fbillno,fprodectno,fzhibaoqi,fu8 from gz_Ypeijian where fbillno = '{$data[0]['fbillno']}' " ,2);
               if(empty($fbillnoArr)){
                   showMsg(1,'数据错误，请检查');
               }
               if(empty($fbillnoArr['fu8'])){
                   showMsg(1,"没有获取U8信息，无法保存！请检查");
               }
               
               $rmbData=['人民币','美元','欧元','日元','英镑','瑞士法郎'];
               $dataEidt=[];
               $dataWhere=[];
               foreach ($data as $k =>&$v)
               {
                   $tempprice = 0 ; 
                   //判断币别是否存在
                   if(!in_array($v['fwaibi'] ,$rmbData ) ){
                       showMsg(1,"币别错误:{$v['fwaibi']}，请检查币别（人民币，美元,欧元,日元,英镑,瑞士法郎）");
                   }
                   if($v['fqtyxq']< $v['fqtykykc']){
                       showMsg(400,"物料号：{$v['fbeijianhao']}，可用库存数大于需求数量") ;
                   }
                   $bbhl = getbb($v['fwaibi'] , $CsData);
                   //计算 
                   if($v['fwaibi'] =='人民币' ){
                       $v['fcaigourmbprice'] = $v['fcaigouybprice'] *$bbhl   ;
                   }else{
                       //现在买需要的采购人民币单价 =  现在采购的采购原币单价 * 汇率*1.06 * (1 + fsetffax / 100)
                       $v['fcaigourmbprice'] = $v['fcaigouybprice'] *$bbhl*1.06 * (1 + $fsetffax / 100) ; 
                   }
                   //现在的采购总价(fcaigouamount)   = 需求数量(fqtyxq) * 现在买需要的采购人民币单价(fcaigourmbprice)
                   $v['fcaigouamount'] = round($v['fqtyxq'] *   $v['fcaigourmbprice'] ,2) ;
                   $v['fcaigourmbprice'] = round( $v['fcaigourmbprice'] ,2) ;
                   //修改
                   $dataEidt['fcaigouybprice'] = $v['fcaigouybprice'];
                   $dataEidt['fcaigouamount'] = $v['fcaigouamount'];
                   $dataEidt['fcaigourmbprice'] = $v['fcaigourmbprice'];
                   $dataEidt['fqtykykc'] = $v['fqtykykc'];
                   $dataEidt['fremark'] = $v['fremark'];
                   $dataEidt['fwaibi'] = $v['fwaibi'];
                   $dataEidt['flrl'] = $fsetlilv ;
                   if($v['fqtykykc'] <= 0){
                      //可用库存数量小于0，用现在买需要的采购人民币单价*（1+利润率）；可用库存数量大于0，
                      //用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
                      //采购单价*（1+利润率）   fcaigourmbprice  现在买需要的采购人民币单价*（1+利润率）
                       $dataEidt['fcbprice'] = $v['fcaigourmbprice'] *(1+ $fsetlilv/100) ;
                   }else{
                       $tempprice = $v['fcaigouprice'] ;
                       //（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在采购单价）*（1+利润率）/需求数量
                       //用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
                       if($v['fkucunprice']>=$v['fcaigouprice']){
                           $tempprice = $v['fkucunprice'];
                       }
                       $dataEidt['fcbprice'] = round( (( $tempprice *(1+$fsetffax/100) * $v['fqtykykc'] + ($v['fqtyxq'] - $v['fqtykykc'])*$v['fcaigourmbprice']) *(1+$fsetlilv/100))/$v['fqtyxq'] ,2) ;
                   }
                   // 成本总价fcbamount
                   $dataEidt['fcbamount'] = $v['fqtyxq']* $dataEidt['fcbprice'] ;
                   
                   $dataWhere['fid'] = $v['fid'];
                   
                   $Tlog[$k]['fbillno'] = $v['fbillno'];
                   $Tlog[$k]['fbeijianhao'] = $v['fbeijianhao'];
                   $Tlog[$k]['fwaibi'] = $v['fwaibi'];
                   $Tlog[$k]['fcaigouybprice'] = $v['fcaigouybprice'];
                 
                   $inEntry = SqlServerUtil::exeupdateTosql($this->SqlServer,'gz_YpeijianEntry',$dataEidt, $dataWhere );
               }
               $this->writeLog(getMkName($FRepKey),'备件采购部导入数据' , $FRepKey , $Tlog ,$opername );
           } else{
               showMsg(1,'数据为空');
           }
        }
        
        if($inEntry  ){
            sqlsrv_commit($this->SqlServer);
            showMsg(0,'导入成功，无须再保存！');
        }else {
            sqlsrv_rollback($this->SqlServer);
            showMsg(1,'导入失败');
        }
    }
    
    
    
    //测试
    public function ceshi(Request $request){ 
    	
    	dd( getYueFenValue('12月') );
    	
    	dd(substr('6X40B-22',0,4) ) ;
    	dd($this->getDTDataU8('D0004503'));
    	
    	dd($this->getDTDataU8('107.262.295.001a'));
    	
    }
    
    
	

}
